const canvas = document.getElementById("mainCanvas")
const cvsw = canvas.width
const cvsh = canvas.height
const ctx = canvas.getContext("2d")

/**
 * const variables
 */
const s = 50 // side length
let x = cvsw/2 - s/2  // x point position for Rect
let y = 0 // y point position for Rect
const dx = 2 // move distance for horizen
const dy = 2 // move distance for vertical

/**
 * enumerate
*/
const Direction = {
  still: 0,
  right: 1,
  left: 2
}
const Bounce = {
  still: 0,
  lifting: 1,
  dropping: 2
}

function initCanvas() {
  /* translate Coordinate System */
  ctx.scale(1, -1)
  ctx.translate(0, -cvsh)
}

function drawChar() {
  ctx.clearRect(0, 0, cvsw, cvsh) // clear canvas
  ctx.fillStyle = "black"
  ctx.fillRect(x, y, s, s)
}

function charMove(direction, distance) {
  let needVibrate = false
  switch(direction) {
    case Direction.right:
      if (x + dx * distance <= cvsw - s) { // bound check
        x += dx * distance
      }else {
        if (x == cvsw - s) {
          needVibrate = true
        }else {
          x = cvsw -s
        }
      }
      break
    case Direction.left:
      if (x - dx * distance >= 0) { // bound check
        x -= dx * distance
      }else {
        if (x == 0) {
          needVibrate = true
        }else {
          x = 0
        }
      }
      break
    default:
      break
  }
  return needVibrate
}

function charBounce(bounceWay, velocity) {
  if (bounceWay == Bounce.lifting) {
    y += parseInt(velocity / 10)
  }else if (bounceWay == Bounce.dropping)
    y -= parseInt(velocity / 10)
}

function updateCanvas(bounceWay, velocity, direction, distance) {
  charBounce(bounceWay, velocity)
  let needVibrate = charMove(direction, distance)
  drawChar()
  return needVibrate
}

initCanvas()
drawChar()